import React, { Component } from 'react'
import { Table, Select, Tooltip, Spin, message, Modal } from 'antd'
import iscroll from 'iscroll'
import cookie from 'js-cookie'
import { axios } from '../../../Utils/index'

import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')

const { Option } = Select
const { confirm } = Modal

export default class CommonTable extends Component {
    constructor (...props) {
        super(...props)
        this.state = {
            columns: [
                {
                    title: () => {
                        return (<span href='/'>关注</span>)
                    },
                    dataIndex: 'attentions',
                    key: '1',
                    dataId: '',
                    width: 60,
                    fixed: 'left',
                    render: (t, r) => {
                        let id = r.fundId
                        if (r.isFav === 0) {
                            return (<span data-id={`${id}`} id={`${id}`} className={`iconfont iconguanzhu heart_check`} onClick={this.headerCheck.bind(this)} />)
                        } else {
                            return (<span data-id={`${id}`} id={`${id}`} className={`iconfont iconyiguanzhu heart_check`} onClick={this.headerCheck.bind(this)} />)
                        }
                    }
                },
                // {
                //     title: '对比',
                //     dataIndex: 'compare',
                //     key: '2',
                //     dataId: '',
                //     width: 60,
                //     fixed: 'left',
                //     render: (t, r) => {
                //         const status = this.state.stroageId.indexOf(`${r['fundId']}`) !== -1 ? true : false
                //         return (<Checkbox checked={status} id={`${r['fundId']}`} name={r['fundName']} onChange={this.changes}></Checkbox>)
                //     }
                // },
                {
                    title: '序号',
                    dataIndex: 'key',
                    width: 60,
                    fixed: 'left',
                    key: '2',
                    dataId: '',
                    render: (text) => (<span>{text!== '' ? text : '--'}</span>)
                },
                {
                    title: '产品名称',
                    sorter: true,
                    fixed: 'left',
                    sortDirections: ['descend', 'ascend'],
                    dataIndex: 'fundName',
                    key: '3',
                    width: 200,
                    ellipsis: true,
                    dataId: '',
                    className:'ellipse_td',
                    render: (text, recoder) => (<Tooltip placement="bottom" title={text}><a className='table_color table_href' rel="noopener noreferrer" target="_blank" href={`/product?id=${recoder.fundId}&name=${encodeURI(text)}`}>{text ? text : '--'}</a></Tooltip>)
                },
                {
                    title: '投资顾问',
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    dataIndex: 'fundConsultant',
                    key: '4',
                    width: 130,
                    dataId: '',
                    ellipsis: true,
                    render: (text, recoder) => (<a  className='table_color table_href' rel="noopener noreferrer" target="_blank" href={`/advisor?id=${recoder.orgId}`}>{text ? text : '--'}</a>)
                },

                {
                    title: '投资经理',
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    dataIndex: 'fundManager',
                    key: '5',
                    dataId: '',
                    width: 130,
                    ellipsis: true,
                    render: (text, recoder) => (<a className='table_color table_href' rel="noopener noreferrer" target="_blank" href={`/manager?id=${recoder.fundManagerId}`}>{text ? text : '--'}</a>)
                },
                {
                    title: '资产类别',
                    sorter: true,
                    key: '6',
                    dataId: '',
                    width: 130,
                    dataIndex: 'assetType',
                    sortDirections: ['descend', 'ascend'],
                    render: (text) => {
                        let content = text ? text : '--'
                        return (<span>{content}</span>)
                    }
                },
                {
                    title: '投资策略',
                    sorter: true,
                    key: '7',
                    dataId: '',
                    width: 130,
                    dataIndex: 'strategyType',
                    sortDirections: ['descend', 'ascend'],
                    render: (text) => {
                        let content = text ? text : '--'
                        return (<span>{content}</span>)
                    }
                },
                {
                    title: '产品成立日期',
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    key: '8',
                    width: 150,
                    dataId: '',
                    dataIndex: 'fundFoundationDate',
                    render: text => (<span>{text ? moment(new Date(text)).format('YYYY-MM-DD') : '--'}</span>)
                },
                {
                    title: '产品星级',
                    sorter: true,
                    key: '9',
                    dataId: '',
                    dataIndex: 'fundStar',
                    sortDirections: ['descend', 'ascend'],
                    render: (text) => {
                        let content = text === undefined ? 0 : text
                        let renderStar = []
                        for (let i = 0; i < 5; i++) {
                            if (i < content) {
                                renderStar.push(<span key={i} className={`iconfont home_table_icon iconxingji icon_color_star`}></span>)
                            } else {
                                renderStar.push(<span key={i} className={`iconfont home_table_icon iconxingji`}></span>)
                            }
                        }

                        return (renderStar)
                    }
                },
                {
                    title: '投顾星级',
                    sorter: true,
                    key: '10',
                    dataId: '',
                    dataIndex: 'consultantStar',
                    sortDirections: ['descend', 'ascend'],
                    render: (text) => {
                        let content = text === undefined ? 0 : text
                        let renderStar = []
                        for (let i = 0; i < 5; i++) {
                            if (i < content) {
                                renderStar.push(<span key={i} className={`iconfont home_table_icon iconxingji icon_color_star`}></span>)
                            } else {
                                renderStar.push(<span key={i} className={`iconfont home_table_icon iconxingji`}></span>)
                            }
                        }

                        return (renderStar)
                    }
                },
                {
                    title:  '累计净值',
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    key: '11',
                    dataId: '',
                    className: 'fund_nav_filters',
                    dataIndex: 'fundNav',
                    render: (text) => {
                        let content = text === undefined ? '--' : text
                    return (<span>{`${isNaN(parseFloat(content)) ? '--' : parseFloat(content).toFixed(4)}`}</span>)
                    }
                },
                {
                    title: () => (
                    <div className='home_table_rate'>
                        <span>收益率</span>
                        <Select
                        id='rateSelection'
                        value={'year'}
                        open={this.state.rateStatus}
                        onChange={this.fundInto}>
                        <Option className={'rate_select_options'} value="year">今年以来</Option>
                        <Option className={'rate_select_options'} value="m1">近一月</Option>
                        <Option className={'rate_select_options'} value="m3">近三月</Option>
                        <Option className={'rate_select_options'} value="m6">近六月</Option>
                        <Option className={'rate_select_options'} value="y1">近一年</Option>
                        <Option className={'rate_select_options'} value="y2">近二年</Option>
                        <Option className={'rate_select_options'} value="y3">近三年</Option>
                        <Option className={'rate_select_options'} value="total">成立以来年化</Option>
                        </Select>
                    </div>
                ),
                    sorter: true,
                    key: '12',
                    dataId: '',
                    width: 130,
                    dataIndex: 'nReturn',
                    sortDirections: ['descend', 'ascend'],
                    onClick: (event) => {console.log(event)},
                    render: (text) => {
                        let content = text === undefined ? '--' : text
                        return (<span className={content > 0 ? 'color_number_red' : 'color_number_green'}>{`${isNaN(parseFloat(content)) ? '--' : parseFloat(content).toFixed(2)+'%'}`}</span>)
                    }
                },
                {
                    title: () => {
                        return (<div className='home_table_rate'>
                            <span>排名</span>
                            <Select
                             id='selectMarket'
                             value={'selectValue'}
                             >
                            <Option className={'market_options'} value="selectValue">同策略</Option>
                            <Option className={'market_options'} value="marketValue">全市场</Option>
                            </Select></div>)
                    },
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    key: '13',
                    dataId: '',
                    width: 130,
                    dataIndex: 'cRank',
                    render: (text) => {
                        let content = text === undefined ? '--' : text
                        return (<span>{content ? content : '--'}</span>)
                    }
                },
                {
                    title: '最大回撤',
                    sorter: true,
                    key: '14',
                    dataId: '',
                    width: 130,
                    dataIndex: 'maxDrawdown',
                    sortDirections: ['descend', 'ascend'],
                    render: (text) => {
                        let content = text === undefined ? '--' : text
                        return (<span className={content > 0 ? 'color_number_red' : 'color_number_green'}>{`${isNaN(parseFloat(content)) ? '--' : parseFloat(content).toFixed(2)}`}</span>)
                    }
                },
                {
                    title: 'Sharpe比率',
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    key: '15',
                    dataId: '',
                    width: 130,
                    dataIndex: 'sharpeA',
                    render: (text) => {
                        let content = text === undefined ? '--' : text
                        return (<span>{`${isNaN(parseFloat(content)) ? '--' : parseFloat(content).toFixed(2)}`}</span>)
                    }
                },
                {
                    title: '信息比率',
                    sorter: true,
                    sortDirections: ['descend', 'ascend'],
                    key: '16',
                    dataId: '',
                    width: 130,
                    dataIndex: 'infoA',
                    render: (text) => {
                        let content = text === undefined ? '--' : text
                        return (<span>{`${isNaN(parseFloat(content)) ? '--' : parseFloat(content).toFixed(2)}`}</span>)
                    }
                }
            ],
            dataSource: [],
            stroageId: window.sessionStorage.getItem('stroageId') ? window.sessionStorage.getItem('stroageId') : [],
            pageSize: 10,
            pageNo: 1,
            count: 0,
            takeDate: new Date().getTime()
        }
    }

    async _init (param) {
        let dataSource = [], count = '', takeDate = ''
        if (this.props._initData) {
            let parmas = { pageNo: this.state.pageNo, pageSize: this.state.pageSize, ...param }
            const data = await this.props._initData(parmas)
            this.setState({loading: false})
            if (data) {
                dataSource = data.orgFunds
                count = data.sumcount
                takeDate = data.takeDate
            }

            if (dataSource.length > 0) {
                dataSource.forEach((item, index) => {
                    item['key'] = index + ((parmas.pageNo - 1) * parmas.pageSize) + 1
                })
                
                await this.setState({dataSource: dataSource, count: count, takeDate: takeDate})
            }
        }
       
    }

    addGroup = (e, target) => {

        axios({
            method: 'POST',
            url: '/api/hszcpz/attention/addAttention',
            data: JSON.stringify({
                "token": cookie.get('token'),
                "fgroup_id":"1003",
                "fav_object_id": e
            })}
        )
        .then(data => {
            message.destroy()
            if (data.status !== 'success') {
                message.info(data.errorReason)
                return
            }
            data = JSON.parse(data.result)

            if (data.result === 'success') {
                target.setAttribute('class', 'iconfont heart_check iconyiguanzhu')
                this.setState({visible: false})
                message.success(data.reason)
            } else {
                message.error(data.reason)
            }
        })

    }

    headerCheck = (e) => {
        let _this = this
        let status = e.target.getAttribute('class')
        let id = e.target.getAttribute('data-id')
        const element = e.target
        if (status.indexOf('iconguanzhu') !== -1) {
            const target = e.target
            this.addGroup(id, target)
        } else {
            confirm({
                title: '取消关注',
                content: '您确定要取消关注本产品吗？',
                okText: '确定',
                centered: true,
                cancelText: '取消',
                onOk: () => {
                    axios({
                        method: 'POST',
                        url: '/api/hszcpz/attention/delAttention',
                        data: JSON.stringify({
                            "token": cookie.get('token'),
                            "fgroup_id":"1003",
                            "fav_object_id": id
                        })}
                    )
                    .then(data => {
                        document.getElementById(id).setAttribute('class', 'iconfont iconguanzhu heart_check')
                        if (data.status !== 'success') {
                            message.info(data.errorReason)
                            return
                        }
                        data = JSON.parse(data.result)

                        if (data.result === 'success') {
                            element.setAttribute('class', 'iconfont iconguanzhu heart_check')
                            _this.setState({visible: false})
                        } else {
                            message.destroy()
                            message.error(data.reason)
                        }
                    })
                },
                onCancel () {}
            })
        }

    }

    async changePageNo (pagination, filter, sorter, e) {
        this.setState({loading: true})
        let sorterItem = `${sorter.field}Sort`
        let sortList = {descend: 'desc', ascend: 'asc'}
        const orderIt = sorter.order
        const { current, pageSize } = pagination
        let sorterOption = {}
        sorterOption[sorterItem] = sortList[orderIt]
        await this.setState({pageNo: current, pageSize: pageSize})
        // console.log(pageSize)
        let params = {pageNo: current, pageSize: pageSize, ...sorterOption}
        await this._init(params)
    }

    async UNSAFE_componentWillMount () {
        this._init()
    }
    componentDidMount () {
        ;(() => {
            new iscroll('.customer_table_bar .ant-table-body', {
                scrollbars: 'custom',
                mouseWheel: false,
                preventDefault: false,
                scrollX: true,
                interactiveScrollbars: true,
                shrinkScrollbars: false,
                bounce: false
            })
        })()
    }

    componentDidUpdate () {}

    render () {
        const { columns, count, dataSource, pageNo, pageSize, takeDate } = this.state
        return <Spin spinning={this.state.loading}><Table className={`customer_table_bar common_table_align_center`}
         dataSource={dataSource} columns={columns} loading={this.props.loading} 
         onChange={this.changePageNo.bind(this)}
         pagination={
            this.state.count > 1 ? {
               showSizeChanger: true,
               current: pageNo,
               pageSize: pageSize,
               showQuickJumper: true,
               pageSizeOptions: ['10', '20', '50', '100'],
               total: (count),
               showTotal: (total) => <span className={'table_data_total'}>共<i className={'color_red total_data_size'}>{dataSource.length > 0 ? count || total: '0'}</i>条数据 <strong>更新日期： <i>{moment(takeDate).format('YYYY-MM-DD')}</i></strong></span>
            } : false
        } scroll={{x: 16 * 130}} /></Spin>
    }
}